<template>
  <div class="login">
    <div class="login-form">
      <div class="flex justify-center mb-26px">
        <img src="@/assets/images/large-logo.png" alt="大图标" />
      </div>
      <h3 class="title">{{ title }}</h3>
      <!-- 账号密码登录 -->
      <div v-if="isPassword">
        <el-form
          ref="passwordLoginRef"
          :model="passwordLoginForm"
          :rules="passwordLoginRules"
        >
          <el-form-item prop="phoneNumber">
            <el-input
              v-model="passwordLoginForm.phoneNumber"
              type="text"
              size="large"
              auto-complete="off"
              placeholder="手机号码"
            >
              <template #prefix>
                <svg-icon
                  icon-class="phone"
                  class="el-input__icon input-icon"
                />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="passwordLoginForm.password"
              type="password"
              size="large"
              auto-complete="off"
              placeholder="请输入密码"
              @keyup.enter="handlePasswordLogin"
            >
              <template #prefix>
                <svg-icon
                  icon-class="password"
                  class="el-input__icon input-icon"
                />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="code" v-if="captchaEnabled">
            <el-input
              v-model="passwordLoginForm.code"
              size="large"
              auto-complete="off"
              placeholder="验证码"
              style="width: 63%"
              @keyup.enter="handlePasswordLogin"
            >
              <template #prefix>
                <svg-icon
                  icon-class="validCode"
                  class="el-input__icon input-icon"
                />
              </template>
            </el-input>
            <div class="login-code">
              <img
                :src="codeUrl"
                @click="getCaptchaImage"
                class="login-code-img"
                alt="验证码"
              />
            </div>
          </el-form-item>
          <div class="flex justify-between">
<!--            <el-checkbox-->
<!--              v-model="passwordLoginForm.rememberMe"-->
<!--              style="margin: 0 0 25px 0"-->
<!--              fill="#5CD0C2"-->
<!--              class="remember-checkbox"-->
<!--            >-->
<!--              记住密码-->
<!--            </el-checkbox>-->
            <el-button
              link
              type="primary"
              style="padding-bottom: 26px"
              @click="handleSwitchPhoneLogin"
            >
              短信登录&gt;&gt;
            </el-button>
            <!-- <i  class="el-icon-d-arrow-right"></i> -->
          </div>

          <el-form-item style="width: 100%">
            <el-button
              :loading="loading"
              size="large"
              type="primary"
              color="#304156"
              style="width: 100%"
              @click.prevent="handlePasswordLogin"
            >
              <span v-if="!loading" class="c-white">登录</span>
              <span v-else class="c-white">登录中...</span>
            </el-button>
            <div style="float: right" v-if="register">
              <router-link class="link-type" :to="'/register'">
                立即注册
              </router-link>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <!-- 短信登录 -->
      <div v-else>
        <el-form ref="smsLoginRef" :model="smsLoginForm" :rules="smsLoginRules">
          <el-form-item prop="phoneNumber">
            <el-input
              v-model="smsLoginForm.phoneNumber"
              type="text"
              size="large"
              auto-complete="off"
              placeholder="手机号码"
            >
              <template #prefix>
                <svg-icon
                  icon-class="phone"
                  class="el-input__icon input-icon"
                />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="smsCode" class="code-item">
            <el-input
              v-model="smsLoginForm.smsCode"
              size="large"
              auto-complete="off"
              placeholder="请输入验证码"
              @keyup.enter="handlePasswordLogin"
              class="w-63%!"
            >
              <!--            style="width: 63%;"-->
              <template #prefix>
                <svg-icon
                  icon-class="validCode"
                  class="el-input__icon input-icon"
                />
              </template>
            </el-input>
            <el-button
              class="w-35%"
              size="large"
              type="primary"
              @click="showBehaviorCheckCode"
              :disabled="requestSmsButtonDisabled"
            >
              {{ requestSmsButtonText }}
            </el-button>
          </el-form-item>
          <div class="flex justify-between">
            <el-button
              link
              type="primary"
              style="padding-bottom: 26px"
              @click="handleSwitchPhoneLogin"
            >
              &lt;&lt;账号密码登录
            </el-button>
            <!-- <i  class="el-icon-d-arrow-right"></i> -->
          </div>
          <el-form-item style="width: 100%">
            <el-button
              :loading="loading"
              size="large"
              type="primary"
              color="#304156"
              style="width: 100%"
              @click.prevent="handleSmsLogin"
            >
              <span v-if="!loading" class="c-white">登录</span>
              <span v-else class="c-white">登录中...</span>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <Verify
      mode="pop"
      captchaType="blockPuzzle"
      :imgSize="{ width: '400px', height: '200px' }"
      ref="verify"
      @success="handleVerifySuccess"
    ></Verify>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © {{ copyright }}.</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  getCaptchaImage as getCaptchaImageApi,
  requestLoginSmsCaptcha as requestLoginSmsCaptchaApi,
} from "@/service/api/login";
// import Cookies from 'js-cookie';
// import { encrypt, decrypt } from '@/utils/jsencrypt';
import { useUserStore } from "@/store/modules/user";
// import { LoginData, TenantVO } from '@/api/types';
import { FormRules } from "element-plus";
import { to } from "await-to-js";
import defaultSettings from "@/settings";
import SvgIcon from "@/components/SvgIcon/index.vue";
import Verify from "@/components/verifition/Verify.vue";

const title = ref(defaultSettings.title);
const copyright = ref(defaultSettings.copyright);

const userStore = useUserStore();
const router = useRouter();

/**
 * 账号密码登录表单
 */
const passwordLoginForm = ref<any>({
  phoneNumber: "",
  password: "",
  code: "",
  uuid: "",
  rememberMe: false,
});

/**
 * 短信验证码登录表单
 */
const smsLoginForm = ref<any>({
  phoneNumber: "",
  smsCode: "",
});

let requestSmsTimer: NodeJS.Timeout | null = null;
let requestSmsCounter = 61;
const requestSmsButtonText = ref("获取验证码");
const requestSmsButtonDisabled = ref(false);
// const requestSmsButtonStyle = ref("primary");

const passwordLoginRules: FormRules = {
  phoneNumber: [
    { required: true, trigger: "blur", message: "请输入您的手机号" },
  ],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }],
};

const smsLoginPhoneNumberRules: FormRules = {
  phoneNumber: [
    { required: true, trigger: "blur", message: "请输入您的手机号" },
    {
      pattern: /^1[3-9]\d{9}$/,
      trigger: "blur",
      message: "请输入正确的手机号",
    },
  ],
};

const smsLoginAllRules: FormRules = {
  phoneNumber: [
    { required: true, trigger: "blur", message: "请输入您的手机号" },
    {
      pattern: /^1[3-9]\d{9}$/,
      trigger: "blur",
      message: "请输入正确的手机号",
    },
  ],
  smsCode: [{ required: true, trigger: "blur", message: "请输入您的验证码" }],
};

const smsLoginRules: Ref<FormRules> = ref(smsLoginAllRules);

const codeUrl = ref("");
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(false);

// 注册开关
const register = ref(false);
const redirect = ref(undefined);
const passwordLoginRef = ref(ElForm);
const smsLoginRef = ref(ElForm);

// 滑动验证码组件
const verify = ref(null);

/**
 * 处理密码登录
 */
const handlePasswordLogin = () => {
  passwordLoginRef.value.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      // if (loginForm.value.rememberMe) {
      //     Cookies.set('username', loginForm.value.username, { expires: 30 });
      //     Cookies.set('password', String(encrypt(loginForm.value.password)), { expires: 30 });
      //     Cookies.set('rememberMe', String(loginForm.value.rememberMe), { expires: 30 });
      // } else {
      //     // 否则移除
      //     Cookies.remove('username');
      //     Cookies.remove('password');
      //     Cookies.remove('rememberMe');
      // }
      // 调用action的登录方法
      // prittier-ignore
      const [err] = await to(userStore.login(passwordLoginForm.value));
      if (!err) {
        loading.value = false;

        await router.push({ path: redirect.value || "/" });
      } else {
        loading.value = false;
        // 重新获取验证码
        if (captchaEnabled.value) {
          await getCaptchaImage();
        }
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

/**
 * 处理短信登录
 */
const handleSmsLogin = () => {
  // 验证全部字段
  smsLoginRules.value = smsLoginAllRules;
  nextTick(() => {
    smsLoginRef.value.validate(async (valid: boolean) => {
      if (valid) {
        loading.value = true;
        const [err] = await to(userStore.smsLogin(smsLoginForm.value));
        if (!err) {
          loading.value = false;

          await router.push({ path: redirect.value || "/" });
        } else {
          loading.value = false;
        }
      }
    });
  });
};

const isPassword = ref(false);
/**
 * 切换密码/短信登录按钮
 */
const handleSwitchPhoneLogin = () => {
  isPassword.value = !isPassword.value;
};

/**
 * 获取验证码
 */
const getCaptchaImage = async () => {
  const [err, res] = await to(getCaptchaImageApi());
  if (!err) {
    const { data } = res;
    captchaEnabled.value =
      data?.captchaEnabled == undefined ? true : data.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + data?.img;
      passwordLoginForm.value.uuid = data?.uuid;
    }
  }
};

/**
 * 获取滑动验证码
 */
const showBehaviorCheckCode = () => {
  // 只校验手机号是否正确
  smsLoginRules.value = smsLoginPhoneNumberRules;
  nextTick(() => {
    smsLoginRef.value.validate(async (valid: boolean, _ /*fields*/ : any) => {
      if (valid) {
        verify.value?.show();
      }
    });
  });
};

/**
 * 滑动验证码处理成功
 * @param res
 */
const handleVerifySuccess = async (res: object) => {
  // smsLoginForm.value.captchaVO = res;
  const [err] = await to(
    requestLoginSmsCaptchaApi(smsLoginForm.value.phoneNumber, res),
  );
  if (!err) {
    requestSmsButtonDisabled.value = true;
    requestSmsTimer = setInterval(() => {
      if (requestSmsCounter > 1) {
        requestSmsCounter--;
        requestSmsButtonText.value = requestSmsCounter.toString();
      } else {
        requestSmsCounter = 61;
        requestSmsButtonText.value = "获取验证码";
        requestSmsButtonDisabled.value = false;
        clearInterval(Number(requestSmsTimer));
      }
    }, 1000);
    ElMessage({
      message: "短信验证码发送成功",
      type: "success",
    });
  }
};

// const getCookie = () => {
// const username = Cookies.get('username');
// const password = Cookies.get('password');
// const rememberMe = Cookies.get('rememberMe');
// loginForm.value = {
//     username: username === undefined ? loginForm.value.username : username,
//     password: password === undefined ? loginForm.value.password : (decrypt(password) as string),
//     rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
// };
// };

onMounted(() => {
  // getCaptchaImage();
  // getCookie();
});
</script>

<style lang="scss" scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
  background-image: url("../assets/images/login-background.png");
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center center;
}

.title {
  margin: 0 auto 30px auto;
  font-size: 30px;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  box-shadow: 0 1px 16px 1px rgba(0, 0, 0, 0.10);

  .el-input {
    height: 40px;

    input {
      height: 40px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 40px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #999999;
  font-family: Arial, serif;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 40px;
  padding-left: 12px;
}

:deep(.remember-checkbox.is-checked) {
  .el-checkbox__input {
    //选中
    .el-checkbox__inner {
      border-color: transparent !important;
      background-color: #5cd0c2;

      &::after {
        // 里面的对钩
        border-color: #fff;
      }
    }
  }

  .el-checkbox__label {
    color: #5cd0c2;
  }
}

:deep(.code-item) {
  .el-form-item__content {
    display: flex;
    justify-content: space-between;
  }
}
</style>
